package com.ourhours.message.listener;

import com.alibaba.fastjson.JSON;
import com.ourhours.message.constant.ConstantMQ;
import com.ourhours.message.domain.AppPush;
import com.ourhours.message.domain.SmsSend;
import com.ourhours.message.dto.AppPushDto;
import com.ourhours.message.dto.PushResponse;
import com.ourhours.message.enums.ApiResponseCode;
import com.ourhours.message.exception.MessageException;
import com.ourhours.message.service.AppPushService;
import com.ourhours.redismq.AbstarctMessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class AppPushMqListener extends AbstarctMessageHandler {

    @Autowired
    AppPushService appPushService;

    public AppPushMqListener() {
        // 说明该handler监控的消息类型，第一个参数是队列名称，第二个参数为重试次数
        super(ConstantMQ.appPushMQ, 1);
    }


    @Override
    public void handle(String text) {
        log.info("==>SmsMqListener.receiveQueueForSms 监听MQ报文为:{}", text);
        AppPushDto dto = null;
        try {
            dto = JSON.parseObject(text, AppPushDto.class);
            if (dto == null || (dto.getId() == null && dto.getVendorId() == null)) {
                throw new MessageException("接收的报文格式不对，转型后结果为null");
            }
            PushResponse push = appPushService.pushing(dto.getVendorId(),dto.getTarget(),dto.getTitle(),dto.getContent(),dto.getAction());
            if(push.getCode()!=200){
                log.info("==>AppPushMqListener.receiveQueueForAppPush 监听MQ报文为:{}，调用发送推送service运行完毕！", text);
                new RuntimeException("调用极光推送失败,参数:{},结果：{}"+text+","+push);
            }
            log.info("==>AppPushMqListener.receiveQueueForAppPush 监听MQ报文为:{}，调用发送推送service运行完毕！", text);
            appPushService.setAppPushStatus(dto.getId(), 1, null, null);
        } catch (Exception e) {
            log.error("==>AppPushMqListener.receiveQueueForAppPush 监听MQ报文为:{}，调用发送推送service运行异常:{}", text, e);
            if (dto != null && dto.getId() != null) {
                appPushService.setAppPushStatus(dto.getId(), -1, ApiResponseCode.ERROR.getCode(), e.getMessage());
            }
        }
    }

    @Override
    public void handleFailed(String s) {

    }
}
